package com.example.springstudy.controller;

import com.example.springstudy.base.Result;
import com.example.springstudy.base.annotation.SaveLog;
import com.example.springstudy.entity.Supplier;
import com.example.springstudy.service.SupplierService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/api/supplier")
public class SupplierController {
    @Autowired
    SupplierService supplierService;

    @GetMapping("/list")
    public Result<?> getAll(){
        return Result.success(supplierService.findAll());
    }

    @SaveLog("修改供应商")
    @PostMapping("/addOrUpdate")
    public Result<?> addOrUpdate(@RequestBody Supplier supplier){
        try{
            Assert.hasText(supplier.getName(), "supplier.name 不能为空！");
            if(supplier.getId() == null || supplier.getId() == 0){
                return Result.success(supplierService.add(supplier));
            } else {
                return Result.success(supplierService.update(supplier));
            }
        } catch (Exception e){
            return Result.failed(e.getMessage());
        }
    }

    @SaveLog("删除供应商")
    @DeleteMapping("/delete")
    public Result<Integer> delete(@RequestParam int id){
        return Result.success(supplierService.delete(id));
    }
}
